package com.soft.link.Interceptor;

import com.soft.link.impl.RedisService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * company 重庆庆云石油工程技术有限责任公司
 * FileName CommonInterceptor
 * Package com.soft.link.Interceptor
 * Description 公用拦截器
 * author Administrator
 * create 2018-04-25 17:11
 * version V1.0
 */
@Component
public class CommonInterceptor implements HandlerInterceptor {
    /**
     * 首页跳转
     */
    // 日志
    private static Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);

    //注入redis 进行集群
    @Autowired(required = false)
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String sessionId = httpServletRequest.getSession().getId();
        logger.info("preHandle------------------------------------开始>");
        /**
         *  跳转登录，进行拦击并记录，进行非法登录记录，并记录对应设备ID，设备类型，及攻击时间
         */
        // String pfToken = PfToken.getCookieValue(httpServletRequest);
        if (StringUtils.isEmpty(sessionId)) {
            logger.info("未登录跳转到登录页--------------->");
            httpServletResponse.sendRedirect("/portal/login");
        } else {
            // 判断当前操作是否超期
            String timeout = redisService.get(sessionId); // 判断是否超时
            if (StringUtils.isEmpty(timeout)) {
                httpServletResponse.sendRedirect("/portal/login");
            } else {
                logger.info("接入权限验证开始--------------->");
                logger.info("接入权限结束开始--------------->");
                return true;
            }
            return true;
        }
        logger.info("preHandle------------------------------------结束>");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("afterCompletion");
    }
}
